package ups.glre.news.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;

import ups.glre.news.dao.GenericDAO;

public abstract class GenericDAOImpl<E, PK extends Serializable> implements
		GenericDAO<E, PK> {

	protected Class<E> entityClass;

	@PersistenceContext(unitName = "PersistenceManager")
	protected EntityManager entityManager;
	
	@SuppressWarnings("unchecked")
	public GenericDAOImpl() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.entityClass = (Class<E>) genericSuperclass
				.getActualTypeArguments()[0];
	}

	public E createObject(E t) {
		this.entityManager.persist(t);
				
		return t;
	}

	public E findObjectById(PK id) {
		return this.entityManager.find(entityClass, id);
	}

	public E updateObject(E t) {
		return this.entityManager.merge(t);
	}

	public void deleteObject(E t) {
			t = this.entityManager.merge(t);
			this.entityManager.remove(t);
	}

	@SuppressWarnings("unchecked")
	public List<E> findAllObject() {	
		
		try { 
			Query query= entityManager.createQuery("SELECT e FROM " + entityClass.getName() + " e");
			return (List<E>) query.getResultList();
		} catch (RuntimeException re) {
			throw re;
		}
	}
}